﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPatterns
{ /// <summary>
  /// 为简单对象和复杂对象声明了通用操作
  /// </summary>
    abstract class Component
    {
        public Component()
        {

        }
        /// <summary>
        /// 操作变量
        /// </summary>
        /// <returns></returns>
        public abstract string Operation();

        public virtual void Add(Component component)
        {
            throw new NotImplementedException();
        }

        public virtual void Remove(Component component)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 是否是复合
        /// </summary>
        /// <returns></returns>
        public virtual bool IsComposite()
        {
            return true;
        }
    }

    /// <summary>
    /// 叶
    /// </summary>
    class Leaf : Component
    {
        public override string Operation()
        {
            return "Leaf";
        }

        public override bool IsComposite()
        {
            return false;
        }
    }

    /// <summary>
    /// 复合对象(里面既包含叶又包含小复合对象)
    /// </summary>
    class Composite : Component
    {
        protected List<Component> _children = new List<Component>();

        public override void Add(Component component)
        {
            this._children.Add(component);
        }

        public override void Remove(Component component)
        {
            this._children.Remove(component);
        }

        public override string Operation()
        {
            int i = 0;
            string result = "包含的分支都有那些：";
            foreach (var component in _children)
            {
                result += component.Operation();
                if (i != _children.Count - 1)
                {
                    result += "+";
                }
                i++;
            }
            return result + ")";
        }
    }

    /// <summary>
    /// 客户端
    /// </summary>
    class Client
    {
        /// <summary>
        /// 组件调用接口   叶子调用
        /// </summary>
        /// <param name="leaf"></param>
        public void ClientCode(Component leaf)
        {
            Console.WriteLine("Result：" + leaf.Operation());
        }

        /// <summary>
        /// 在基组件类中，客户端可以与任何组件，简单和复杂的对象交互，不依赖具体的类
        /// </summary>
        /// <param name="c1"></param>
        /// <param name="c2"></param>
        public void ClientCode2(Component c1, Component c2)
        {
            if (c1.IsComposite())
            {
                c1.Add(c2);
            }
            Console.WriteLine("Result：" + c1.Operation());
        }
    }

}
